/*
Copyright © 2021 NAME HERE <EMAIL ADDRESS>

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package cmd

import (
	"gitee.com/extrame/fb-runner/app"
	"github.com/pkg/errors"
	"github.com/sirupsen/logrus"
	"github.com/spf13/cobra"
)

var approveCfg struct {
	version *int64
	name    *string
}

// approveCmd represents the approve command
var approveCmd = &cobra.Command{
	Use:   "approve",
	Short: "批准安装的代码",
	Long:  ``,
	Run: func(cmd *cobra.Command, args []string) {
		var err error
		if len(args) > 0 {
			code := app.GetInstalledChaincode(args[0])
			if code != nil {
				logrus.Infoln("Approve", code)
				if *approveCfg.version >= 0 {
					logrus.Infoln("手工指定version为", *approveCfg.version)
					code.Version = uint64(*approveCfg.version)
				}
				if *approveCfg.name != "" {
					logrus.Infoln("手工指定部署名称为", *approveCfg.name)
					code.Name = *approveCfg.name
				}
				err = app.Approve(cfg.GetBase(), code)
			} else {
				err = errors.New("没有找到这个package：" + args[0])
			}
		} else {
			err = app.Approve(cfg.GetBase())
		}
		checkErr(err)
	},
}

func init() {
	rootCmd.AddCommand(approveCmd)

	// Here you will define your flags and configuration settings.

	// Cobra supports Persistent Flags which will work for this command
	// and all subcommands, e.g.:
	// approveCmd.PersistentFlags().String("foo", "", "A help for foo")

	// Cobra supports local flags which will only run when this command
	// is called directly, e.g.:
	approveCfg.version = approveCmd.Flags().Int64P("version", "V", 0, "手工指定更新的版本号，以处理自动版本号出错的情况")
	approveCfg.name = approveCmd.Flags().StringP("name", "n", "", "手工指定程序的文件名")
}

func checkErr(err error) {
	if err != nil {
		logrus.Fatal(err)
	}
}
